package com.OrderingServer.Controller.buyer;

import com.OrderingServer.Form.OrderForm;
import com.OrderingServer.WebSocket.WebSocket;
import com.OrderingServer.annotation.LoggerManage;
import com.OrderingServer.convert.OrderForm2OrderDTOConverter;
import com.OrderingServer.dto.OrderDTO;
import com.OrderingServer.enum1.ResultEnum;
import com.OrderingServer.exception.SellException;
import com.OrderingServer.service.IOrderMasterService;
import com.OrderingServer.service.PushMessageService;
import com.OrderingServer.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/sell/buyer")
public class BuyerOrderController {
@Autowired
    IOrderMasterService orderMasterService;
@Autowired
    PushMessageService pushMessageService;
    @Autowired
    WebSocket webSocket;
    @RequestMapping("/order/create")
    @LoggerManage(value = "买家下单")
    public ResultVO createOrder(OrderForm orderForm){
        log.info("--->微信的OpenId:" + orderForm.getOpenid());
        OrderDTO orderDTO = OrderForm2OrderDTOConverter.convert(orderForm);
        //调用下单业务
        OrderDTO order=orderMasterService.createOrder(orderDTO);
        //发送模板消息
        pushMessageService.orderStatus(order);
        log.info("买家下单的数据,进行消息推送："+orderDTO);
        //给卖家推动新的订单消息
        webSocket.sendMessage(order.toString());
        return new ResultVO(0,"成功",order);
    }
    @LoggerManage("买家订单列表")
    @GetMapping("/order/list")
    public ResultVO <List<OrderDTO>> list (@RequestParam ("openid") String openid) {

        if(!StringUtils.hasText(openid)){
            log.error("【查询订单列表】openid为空");
            throw new SellException(ResultEnum.PARAM_ERROR);
        }
        List<OrderDTO> orderDTOS=orderMasterService.findlist(openid);
        return new ResultVO(0,"成功",orderDTOS);
    }
    @LoggerManage("买家订单详情")
    @GetMapping("/order/detail")
    public ResultVO <List<OrderDTO>> list (@RequestParam ("openid") String openid,
                                           @RequestParam ("orderId") String orderid)
    {

       OrderDTO orderDTO=orderMasterService.findOrderInfo(openid,orderid);
        return new ResultVO(0,"成功",orderDTO);
    }
    @LoggerManage("买家取消订单")
    @PostMapping("/order/cancel")
    public ResultVO <List<OrderDTO>> cancel (@RequestParam ("openid") String openid,
                                           @RequestParam ("orderId") String orderid)
    {

     OrderDTO orderDTO=  orderMasterService.buyercancel(openid,orderid);
     OrderDTO orderDTO1=orderMasterService.findOrderInfo(openid,orderid);
        //发送模板消息
        pushMessageService.orderStatus(orderDTO1);
        return new ResultVO(0,"成功",null);
    }
}
